import sys
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
import os
from pathlib import Path

def get_database_url():
    # 从环境变量获取HOME目录
    home_dir = os.getenv('HOME') or os.getenv('USERPROFILE')  # Windows 使用 USERPROFILE
    if not home_dir:
        print("Error: Could not determine home directory")

    # 在HOME目录下创建.timerpos目录
    data_dir = Path(home_dir) / '.timerpos'
    data_dir.mkdir(exist_ok=True)
    
    # 设置数据库路径
    db_path = str(data_dir / 'timerpos.db')
    print(f"Using default database path: {db_path}")


    return f"sqlite:///{db_path}"

SQLALCHEMY_DATABASE_URL = get_database_url()

engine = create_engine(
    SQLALCHEMY_DATABASE_URL,
    connect_args={"check_same_thread": False}
)

SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
Base = declarative_base()

def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()

def init_database():
    """Initialize database tables and create initial data"""
    from . import models  # Import here to avoid circular imports
    
    print("Creating database tables...")
    Base.metadata.create_all(bind=engine)
    
    db = SessionLocal()
    try:
        # Check if admin user exists
        admin = db.query(models.User).filter(models.User.username == "admin").first()
        if not admin:
            from .auth import get_password_hash
            print("Creating admin user...")
            admin = models.User(
                username="admin",
                hashed_password=get_password_hash("admin"),
                is_active=True
            )
            db.add(admin)
        
        # Initialize default categories if none exist
        if db.query(models.Category).count() == 0:
            print("Creating default categories...")
            default_categories = [
                models.Category(name="饮料"),
                models.Category(name="零食"),
                models.Category(name="其它"),
            ]
            db.add_all(default_categories)
        
        # Initialize default room if none exist
        if db.query(models.TimedRoom).count() == 0:
            print("Creating default room...")
            default_room = models.TimedRoom(
                name="房间1",
                minimum_charge=50,
                minimum_hours=2,
                overtime_rate=20,
                status=models.RoomStatus.AVAILABLE.value
            )
            db.add(default_room)
        
        db.commit()
        print("Database initialization completed.")
    except Exception as e:
        print(f"Error during database initialization: {e}")
        db.rollback()
        raise
    finally:
        db.close() 